<template>
  <view class="time-range">
    <picker mode="multiSelector" :range="range" :value="timeValue" @change="bindTimeChange">
      <view v-if="value.length>0">{{ value[0] }} - {{ value[1] }}</view>
      <view v-else>{{ placeholder }}</view>
    </picker>
  </view>
</template>

<script>
export default {
  props: {
    value: {
      type: Array,
      default() {
        return [];
      }
    },
    placeholder: {
      type: String,
      default() {
        return "请选择时间";
      }
    }
  },
  model: {
    prop: "value",
    event: "change"
  },
  data() {
    return {
      range: [],
      timeValue: [],
      arr1: [], // 时
      arr2: [] // 分
    };
  },
  watch: {
    value() {
      this.setDefautValue();
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      // 设置选项
      let arr1 = [];
      let arr2 = [];
      for (let index = 0; index < 24; index++) {
        let v = index + "";
        v = v.length == 2 ? v : "0" + v;
        this.arr1.push(v);
      }
      for (let index = 0; index < 59; index++) {
        let v = index + "";
        v = v.length == 2 ? v : "0" + v;
        this.arr2.push(v);
      }
      this.range = [this.arr1, this.arr2, this.arr1, this.arr2];
      this.setDefautValue();
    },
    setDefautValue() {
      let val1 = (this.value[0] || "").split(":");
      let val2 = (this.value[1] || "").split(":");
      let values = [...val1, ...val2];

      values.forEach((v, index) => {
        let i = index % 2 == 0 ? this.arr1.indexOf(v) : this.arr2.indexOf(v);
        if (i > -1) {
          this.timeValue.push(i);
        }
      });
    },
    bindTimeChange(e) {
      let value = e.detail.value;
      let date1 = this.range[0][value[0]] + ":" + this.range[1][value[1]];
      let date2 = this.range[2][value[2]] + ":" + this.range[3][value[3]];
      // this.value = [date1, date2];
      this.$emit("change", [date1, date2]);
    }
  }
};
</script>

<style scoped lang="scss">
@import "@/static/iconfont/iconfont.css";
.time-range {
}
</style>